package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @Author: Rodgers
 * @Date 2022/3/8 10:50
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired(required = false)
    private EmployeeService employeeService;

    /**
     * 登录
     * @param employee
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){

        //1.调用业务进行登录，获取返回结果
        R<Employee> login = employeeService.login(employee);

        //判断是否登录成功，登录成功把用户的id存储到session
        if (login.getCode()==1){
            session.setAttribute("employee",login.getData().getId());
        }

        return login;
    }

    /**
     * 退出
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }


    /**
     * 新增
     * @param employee
     * @param session
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpSession session){
        //从会话域中获取登录用户的id
        Long id = (Long) session.getAttribute("employee");

        //完善数据
        employee.setUpdateTime(LocalDateTime.now());

        employee.setCreateUser(id);
        employee.setUpdateUser(id);


        //调用业务
        employeeService.save(employee);

        return R.success("注册成功");
    }

    /**
     * 分页查找
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @RequestMapping("/page")
    public R<Page<Employee>> findByPage(Integer page,Integer pageSize,String name){
        Page<Employee> byPage = employeeService.findByPage(page, pageSize, name);
        return R.success(byPage);
    }

    /**
     * 修改
     * @param employee
     * @param session
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        //获得当前的id
        Long id = (Long) session.getAttribute("employee");

        //完善数据修改
        employee.setUpdateUser(id);

        //调用业务修改
        employeeService.update(employee);

        //返回数据
        return R.success("修改成功");
    }

    /**
     * 回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> selectById(@PathVariable Long id){
        R<Employee> employeeR = employeeService.selectById(id);
        return employeeR;
    }
}
